import joblib
import pandas as pd
from django.http import JsonResponse
from django.shortcuts import render

model_path = '/Users/jackiezheng/DjangoLesson/django_titanic_02/titanic_app/titanic_model_20250113_210016.pkl'
try:
    model = joblib.load(model_path)
except FileNotFoundError:
    print(f"模型文件 {model_path} 未找到，请检查文件路径或确保模型已生成。")
    model = None
except Exception as e:
    model = None
    print(f"加载模型时发生错误：{str(e)}")

# Create your views here.

def index(request):
    return render(request, "predict_form.html")

def go_gpt(request):
    return render(request, "chatgpt.html")

def predict(request):
    # return render(request, "predict_form.html")
    #参数接收
    pclass = request.GET.get("pclass", 0)
    sex = request.GET.get("sex", 0)
    age = request.GET.get("age", 0)
    sibsp = request.GET.get("sibsp", 0)
    parch = request.GET.get("parch", 0)
    fare = request.GET.get("fare", 0)
    embarked = request.GET.get("embarked", 0)

    print(f"age是： {age}")

    #模型推理
    input_data = pd.DataFrame([{
        "pclass":pclass,
        "sex": sex,
        "age": age,
        "sibsp": sibsp,
        "parch": parch,
        "fare": fare,
        "embarked": embarked
    }])
    print(f"input_data: {input_data}")
    predict_result = model.predict_proba(input_data)
    print(f"模型推理原始值predict_result: {predict_result}")
    survival_prob = predict_result[:, 1][0]
    print(f"survival_prob: {survival_prob}")

    return JsonResponse({"survival_prob": survival_prob}, status = 200)